<template>
	<view>
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<template #backText>返回</template>
			<template #content>我的卡券</template>
		</cu-custom>

		<view v-if="loading" class="text-center padding-xl">
			<text class="cuIcon-loading2 iconfont-spin"></text>
			<text> 正在加载...</text>
		</view>
		<view v-else-if="cards.length === 0" class="text-center padding-xl text-gray">
			您还没有卡券
		</view>

		<view v-else class="padding-lr-sm padding-tb-xs">
			<view class="cu-card coupon" v-for="card in cards" :key="card.id" :class="getCardStatus(card).class">
				<view class="cu-item shadow-lg">
					<view class="flex">
						<view class="left">
							<view>
								<text class="text-bold text-xxl text-price text-red">{{ card.card_price }}</text>
							</view>
							<view class="text-sm">满{{ card.condition }}元可用</view>
						</view>
						<view class="right">
							<view class="flex justify-between align-start">
								<view>
									<view class="text-bold">{{ card.card_name }}</view>
									<view v-if="card.mer_id !== 0" class="text-sm text-gray margin-top-xs">商家: {{ card.mer_name }}</view>
									<view v-else class="text-sm text-gray margin-top-xs">平台通用券</view>
									<view class="text-xs text-gray margin-top-xs">有效期至: {{ card.expire_time.split('T')[0] }}</view>
								</view>
								<button class="cu-btn round sm" :class="getCardStatus(card).buttonClass" @click="useCard(card)">
									{{ getCardStatus(card).text }}
								</button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { get } from '@/utils/request.js';

const cards = ref([]);
const loading = ref(true);

onLoad(async () => {
	await fetchUserCards();
});

const fetchUserCards = async () => {
	console.log('开始获取用户卡券...');
	loading.value = true;
	try {
		const storedUser = uni.getStorageSync('user');
		console.log('从本地存储中获取的 "user" 信息:', storedUser);

		if (!storedUser) {
			console.log('未找到 "user" 信息，流程提前结束。');
			cards.value = [];
			loading.value = false;
			return;
		}

		const userData = JSON.parse(storedUser);
		const userId = userData.userId;
		console.log('解析出的用户ID:', userId);

		if(!userId) {
			console.log('用户ID不存在，流程提前结束。');
			loading.value = false;
			return;
		}

		const res = await get(`/card/getCardByCardId?userId=${userId}`);
		console.log("后端返回的卡券信息",res)
		if (res.data && res.data.code === 200) {
			cards.value = res.data.msg;
			console.log('卡券数据已成功加载:', cards.value);
		} else {
			cards.value = [];
			console.warn('后端返回数据异常或无卡券:', res);
		}
	} catch (error) {
		console.error('获取用户卡券过程中发生网络或解析错误:', error);
		cards.value = [];
	} finally {
		loading.value = false;
		console.log('获取卡券流程结束。');
	}
};

const getCardStatus = (card) => {
	const now = new Date();
	const expireTime = new Date(card.expire_time);

	if (card.status !== 0) {
		return { text: '已使用', class: 'used', buttonClass: 'bg-grey' };
	}
	if (expireTime < now) {
		return { text: '已过期', class: 'expired', buttonClass: 'bg-grey' };
	}
	return { text: '去使用', class: '', buttonClass: 'bg-red' };
};

const useCard = (card) => {
	if (getCardStatus(card).text === '去使用') {
		if (card.mer_id !== 0) {
			uni.navigateTo({
				url: `/pages/merchat/index?id=${card.mer_id}`
			});
		} else {
			uni.switchTab({
				url: '/pages/index/index'
			});
		}
	}
};
</script>

<style scoped>
.coupon {
	margin-top: 20rpx;
}
.coupon .cu-item {
	border-radius: 16rpx;
	overflow: hidden;
	background-color: #ffffff;
}
.coupon .left {
	width: 200rpx;
	background-color: #fff8f8;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 20rpx 0;
	border-right: 2rpx dashed #eee;
	position: relative;
}
.coupon .left .text-price {
	font-size: 48rpx;
}
.coupon .right {
	flex: 1;
	padding: 20rpx;
}
.expired, .used {
	filter: grayscale(100%);
	opacity: 0.7;
}
.iconfont-spin {
  animation: spin 1s linear infinite;
}
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style> 